//
//  FeelingViewController.m
//  网络FM
//
//  Created by dlios on 15/5/23.
//  Copyright (c) 2015年 dengzhicheng.com. All rights reserved.
//

#import "FeelingViewController.h"
#import "FeelingTableViewCell.h"

#import <AFNetworking.h>
#import <UIImageView+WebCache.h>

#import "SearchAnchorDetailModel.h"

#import "PlayerViewController.h"
#import "GFPlaceholderView.h"

#import "HistoryDatabase.h"
#import "HistoryModel.h"

#import <MJRefresh.h>

@interface FeelingViewController ()
@property (nonatomic, retain)GFPlaceholderView *placeholder;
@property (nonatomic,assign)NSInteger pageChanged;
@end

@implementation FeelingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.placeholder = [[GFPlaceholderView alloc] initWithFrame:CGRectMake(0, - 64, self.view.frame.size.width, self.view.frame.size.height)];
    [_placeholder showLoadingView];
    [self.view addSubview:_placeholder];
    self.navigationItem.title = self.choice;
    
    // 自定义导航栏返回按钮
    UIButton *navButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [navButton addTarget:self action:@selector(navButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [navButton setImage:[UIImage imageNamed:@"返回.jpg"] forState:UIControlStateNormal];
    [navButton setImage:[UIImage imageNamed:@"返回.jpg"] forState:UIControlStateHighlighted];
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:navButton]];
}

// 导航栏返回按钮点击事件
- (void)navButtonClick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.choiceDetailArray = [NSMutableArray array];
        self.urlArray = [NSMutableArray array];
        self.pageChanged = 2;
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)loadView
{
    [super loadView];
    
    [self  SearchConnetion];
    [self createTableView];
    
    self.navigationController.navigationBar.translucent = NO;
}


- (void)createTableView
{
    
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.table.dataSource = self;
    self.table.rowHeight = self.view.frame.size.width / 4 + 20;
    self.table.delegate = self;
    self.table.separatorStyle = UITableViewCellSelectionStyleNone;
    //上拉刷新下拉加载
    [self.table addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(Refresh)];
    [self.table addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(Load)];
    [self.view addSubview:self.table];
    self.table.showsVerticalScrollIndicator = NO;
    [self.table release];
}


#pragma mark -
#pragma mark 上拉刷新 下拉加载
- (void)Refresh
{
    [self.table reloadData];
    [self.table.header endRefreshing];
}
- (void)Load
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [NSString stringWithFormat:@"http://bapi.xinli001.com/fm2/broadcast_list.json/?offset=0&v=1&key=c605710a2343f6da4ac22c8cce194bd0&rows=15&tag="];
    NSString *s = [NSString stringWithFormat:@"%@%@&rows=15&offset=%ld",str,self.choice,self.pageChanged * 15];
    
    
    s = [s stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [manager GET:s parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = [bigDic objectForKey:@"data"];
        //判断是否是最后一条
        if (array.count == 0) {
            [self.table removeFooter];
            return ;
        }
        for (NSMutableDictionary *dic  in array) {
            SearchAnchorDetailModel *model = [[SearchAnchorDetailModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.choiceDetailArray addObject:model];
            
        }
        self.pageChanged += 1;
        [self.table.footer endRefreshing];
        [self.table reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];}


//UITableView的两个必须实现的协议

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionr{
    return self.choiceDetailArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cell";
    FeelingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell) {
        cell = [[FeelingTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentify];
        
    }
    
    SearchAnchorDetailModel *model = [self.choiceDetailArray objectAtIndex:indexPath.row];
    
    [cell.image sd_setImageWithURL:[NSURL URLWithString:model.cover] placeholderImage:[UIImage imageNamed:@"占位图.jpg"] options:SDWebImageRetryFailed];
    cell.FMName.text = model.title;
    cell.anchorName.text =  [NSString stringWithFormat:@"  主播 %@",model.speak];
    NSString * s = [NSString stringWithFormat:@"%ld",(long)model.viewnum];
    NSString *str = [NSString stringWithFormat:@"  收听  %@",s];
    
    cell.listen_count.text =str;
    if (indexPath.row % 2) {
        
        cell.frame = CGRectMake(- self.view.frame.size.width, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        
        [UIView animateWithDuration:0.7 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        } completion:^(BOOL finished) {
            ;
        }];
        
    }
    else{
        
        cell.frame = CGRectMake(self.view.frame.size.width ,cell.frame.origin.y ,cell.frame.size.width, cell.frame.size.height);
        
        [UIView animateWithDuration:0.7 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        } completion:^(BOOL finished) {
            ;
        }];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

//具体心情界面下的网络请求
- (void)SearchConnetion
{
    //choiceDetailcell的网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [NSString stringWithFormat:@"http://bapi.xinli001.com/fm2/broadcast_list.json/?offset=0&v=1&key=c605710a2343f6da4ac22c8cce194bd0&rows=15&tag="];
    NSString *s = [NSString stringWithFormat:@"%@%@",str,self.choice];
    
    
    s = [s stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [manager GET:s parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = [bigDic objectForKey:@"data"];
        for (NSMutableDictionary *dic  in array) {
            SearchAnchorDetailModel *model = [[SearchAnchorDetailModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.urlArray addObject:[dic objectForKey:@"url"]];
            [self.choiceDetailArray addObject:model];
            
        }
        [self createTableView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}



//点击cell,跳转到播放界面,把model传过去
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.table deselectRowAtIndexPath:[self.table indexPathForSelectedRow] animated:YES];
    PlayerViewController *player = [[PlayerViewController alloc]init];
    SearchAnchorDetailModel *model = [self.choiceDetailArray objectAtIndex:indexPath.row] ;
    HistoryModel *history = [[HistoryModel alloc]init];
    history.titleName = model.title;
    history.imageName = model.absolute_url;
    history.videoUrl = model.url;
    history.people = model.speak;
    
    [HistoryDatabase insertWithModel:history];
    
    player.picURL = model.absolute_url;
    player.urlForPlay = model.url;
    player.picURL = model.cover;
    player.tit = model.title;
    player.speaker = model.speak;
    
    UIView *controlView = [self.view.window.subviews objectAtIndex:1];
    [controlView setAlpha:0];
    
    [self.navigationController pushViewController:player animated:YES];
}

@end
